package top.hepingan.java.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import top.hepingan.java.Aiconfig.Auconfigq;
import top.hepingan.java.Aiconfig.ChatHistoryRedis;
import top.hepingan.java.common.Result;
import top.hepingan.java.service.IDeviceUsageService;
import top.hepingan.java.service.IUserService;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;

@RequestMapping("/ai")
@RestController
@Slf4j
@RequiredArgsConstructor
public class AiController {
    @Autowired
    private Auconfigq auconfig;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IDeviceUsageService iDeviceUsageService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ChatHistoryRedis chatHistoryRedis;


    @RequestMapping("/chat")
    public Flux<String> chat(String userMessage) throws Exception {
//       //次数
        int i=iDeviceUsageService.ismember("1L");
        if (i==0||i<0){
            return Flux.just("抱歉，你的次数达到限制，请订阅会员后重试");
        }
//        Flux<String> Resulter = null;
//        try {
//            Resulter =auconfig.chat(1, userMessage);
//        }catch ( Exception e)
//            {
//                log.error("错误信息：{}",e.getMessage());
//                return Flux.just("抱歉，请稍后再试");
//            }
//        //对话记忆
//        chatHistoryRedis.saveChat("1L",userMessage, String.valueOf(Resulter));
//        return Resulter;
        Flux<String> resulter;
        try {
            resulter = auconfig.chat(1, userMessage);
        } catch (Exception e) {
            log.error("错误信息：{}", e.getMessage());
            return Flux.just("抱歉，请稍后再试");
        }
        // 用 ConcurrentLinkedQueue 收集元素，不阻塞 Flux 流
        List<String> replies = new CopyOnWriteArrayList<>();

// 用 resulter 构建一个带保存副作用的 Flux
        Flux<String> trackedResulter = resulter
                .doOnNext(replies::add)
                .doOnComplete(() -> {
                    // 异步保存聊天记录，不阻塞前端
                    Mono.fromRunnable(() -> {
                                try {
                                    chatHistoryRedis.saveChat("1L", userMessage, String.join("\n", replies));
                                } catch (Exception ex) {
                                    log.error("保存聊天记录失败: {}", ex.getMessage());
                                }
                            }).subscribeOn(Schedulers.boundedElastic())
                            .subscribe();
                });

// **返回 trackedResulter** 给 WebFlux，让前端订阅一次
        return trackedResulter;
    }
    /**
     * 开通会员
     * @param deviceId 设备ID
     * @param planType 套餐类型: month=月付, season=季付
     */
    @PostMapping("/open")
    public Result openMember(@RequestParam String deviceId,
                             @RequestParam String planType) {
        return iDeviceUsageService.openMember(deviceId, planType);

    }
    /**
     *  订单列表
     */
    @PostMapping("/selectoride")
    public Result selectoride(@RequestParam String deviceId) {
        return iDeviceUsageService.selectoride(deviceId);
    }
    /**
     * 展示用户聊天记录接口（非流式）
     *
     * @param deviceCode 用户ID
     * @return List<String> 用户历史聊天记录
     */
    @GetMapping("/history")
    public ResponseEntity<List<Map<String, Object>>> getChatHistory(@RequestParam String deviceCode) {
        try {
            List<Map<String, Object>> history = chatHistoryRedis.showHistory(deviceCode);

            if (history.isEmpty()) {
                return ResponseEntity.ok(Collections.singletonList(
                        Map.of("msg", "暂无聊天记录", "create_time", System.currentTimeMillis())
                ));
            }

            return ResponseEntity.ok(history);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonList(
                            Map.of("msg", "获取聊天记录失败，请稍后再试", "create_time", System.currentTimeMillis())
                    ));
        }
    }

}
